from django.contrib import admin
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.utils.safestring import mark_safe

from data.models import Purchase

from data.utils import sync_guizhou_purchases


@admin.register(Purchase)
class PurchaseAdmin(admin.ModelAdmin):
    actions = ['sync_admin_action',]
    list_display = ('id', 'province', 'keyword', 'publish_date', 'title', 'budget_price', 'district_name', 'path_name', 'url_display', 'status')
    list_display_links = ('id',)
    list_filter = ('keyword',)
    search_fields = ('title',)
    search_help_text = '请输入标题查找'
    date_hierarchy = 'publish_date'
    readonly_fields = ('id', 'province', 'keyword', 'author', 'budget_price', 'district_code', 'district_name', 'path_name', 'procurement_method', 'project_code', 'project_name', 'publish_date', 'title', 'content', 'url', 'expire_flag', 'expire_at', 'implementation_date', 'is_gov_purchase', 'create_at', 'update_at',)

    def sync_admin_action(self, request, queryset):
        sync_guizhou_purchases()

    sync_admin_action.short_description = '手动执行同步'
    sync_admin_action.acts_on_all = True

    @admin.display(description='采购详情链接')
    def url_display(self, obj):
        return mark_safe('<a target="_blank" href="%s">%s</a>' % (obj.url, obj.url) if obj.url else 'N/A')

    def changelist_view(self, request, extra_context=None):
        if 'action' in request.POST and request.POST['action'] == 'sync_admin_action':
            if not request.POST.getlist(ACTION_CHECKBOX_NAME):
                post = request.POST.copy()
                for u in Purchase.objects.all():
                    post.update({ACTION_CHECKBOX_NAME: str(u.id)})
                request._set_post(post)
        return super(PurchaseAdmin, self).changelist_view(request, extra_context)
